﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using SARS.Biz;
using SARS.Biz.Facades;
using SARS.Entity;

namespace SARS.Tutor
{
    public partial class EditStudentAttendance : Page
    {
        private readonly ICourseBO _courseBO = new CourseBO();
        private readonly IProgramBO _programmeBO = new ProgramBO();
        private readonly ISessionBO _sessionBO = new SessionBO();
        private readonly IUserBO _userBO = new UserBO();
        private string course_id = string.Empty;
        private string program_id = string.Empty;
        private string session_id = string.Empty;

        private List<AttendanceSessionEntity> AttendanceSessionList
        {
            get { return (List<AttendanceSessionEntity>) Session["AttendanceSessionEntitySession"]; }
            set { Session["AttendanceSessionEntitySession"] = value; }
        }

        private UserEntity CurrentUser
        {
            get { return Session["CurrentUser"] != null ? (UserEntity) Session["CurrentUser"] : null; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                program_id = Request["pid"];
                course_id = Request["cid"];
                session_id = Request["sid"];

                if (!string.IsNullOrEmpty(program_id) &&
                    !string.IsNullOrEmpty(course_id) &&
                    !string.IsNullOrEmpty(session_id))
                {
                    AttendanceSessionList = RetrieveAttendanceSessionById(Convert.ToInt32(Request["sid"]));

                    lblProgram.Text = _programmeBO.RetrieveProgramById(Convert.ToInt32(program_id)).ProgramName;
                    lblCourse.Text = _courseBO.RetrieveCourseById(Convert.ToInt32(course_id)).CourseInfo;
                    lblSession.Text = _sessionBO.RetrieveSessionById(Convert.ToInt32(session_id)).SessionInfo;

                    grvStudents.DataSource = RetrieveStudentList();
                    grvStudents.DataBind();
                }
                else
                {
                    Response.Redirect("StudentAttendance.aspx");
                }
            }
        }

        private List<UserEntity> RetrieveStudentList()
        {
            session_id = Request["sid"];
            return
                _userBO.RetrieveUserByRoleId((int) RoleType.Student)
                    .Where(
                        x =>
                            AttendanceSessionList.Any(
                                y => y.StudentID == x.UserID && y.SessionID == Convert.ToInt32(session_id)))
                    .ToList();
        }

        private List<AttendanceSessionEntity> RetrieveAttendanceSessionById(int id)
        {
            return _sessionBO.RetrieveAttendanceSessionBySessionId(id);
        }

        protected void grvStudents_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //int x = Convert.ToInt32(e.Row.RowIndex);
                var chk = (CheckBox) e.Row.FindControl("ckbIsAbsent");
                var hdf = (HiddenField) e.Row.FindControl("hdnStudentID");

                int count =
                    AttendanceSessionList.Count(
                        x => x.SessionID == Convert.ToInt32(Request["sid"]) && x.StudentID == Convert.ToInt32(hdf.Value));

                chk.Checked = count > 0;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            List<AttendanceSessionEntity> attendanceSessionEntities = (from GridViewRow row in grvStudents.Rows
                let cbxIsAbsent = (CheckBox) row.FindControl("ckbIsAbsent")
                where cbxIsAbsent.Checked
                select new AttendanceSessionEntity
                {
                    SessionID = Int32.Parse(Request["sid"]),
                    StudentID = Int32.Parse(((HiddenField) row.FindControl("hdnStudentID")).Value),
                    IsAbsent = cbxIsAbsent.Checked ? 1 : 0,
                    Creator = 1,
                    CreatedDate = DateTime.Now
                }).ToList();

            if (attendanceSessionEntities.Count > 0)
            {
                List<AttendanceSessionEntity> registeredStudentAttendance = AttendanceSessionList;

                List<AttendanceSessionEntity> existingAttendanceSession =
                    (attendanceSessionEntities.Where(
                        x =>
                            registeredStudentAttendance.Any(
                                y => y.SessionID == x.SessionID && y.StudentID == x.StudentID))).ToList();

                //var newAttendanceSession = (attendanceSessionEntities.Where(x => !registeredStudentAttendance.Any(y => y.SessionID == x.SessionID && y.StudentID == x.StudentID))).ToList();
                List<AttendanceSessionEntity> uncheckedAttendanceSession =
                    (registeredStudentAttendance.Where(
                        x =>
                            !attendanceSessionEntities.Any(y => y.SessionID == x.SessionID && y.StudentID == x.StudentID)))
                        .ToList();

                if (existingAttendanceSession.Count > 0)
                {
                    foreach (AttendanceSessionEntity entity in existingAttendanceSession)
                    {
                        entity.ModifiedBy = CurrentUser.UserID;
                        entity.ModifiedDate = DateTime.Now;
                        _sessionBO.UpdateAttendanceSessionById(entity);
                    }
                }
                //if (newAttendanceSession.Count > 0)
                //{
                //    _sessionBO.InsertAttendanceSession(newAttendanceSession);
                //}
                if (uncheckedAttendanceSession.Count > 0)
                {
                    foreach (AttendanceSessionEntity entity in uncheckedAttendanceSession)
                    {
                        _sessionBO.DeleteAttendanceSessionById(entity.ID);
                    }
                }

                Response.Redirect("StudentAttendance.aspx");
            }
        }
    }
}